package com.ys.aop;

import com.ys.modules.system.entity.OperationLog;
import com.ys.modules.system.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private OperationLogService operationLogService;

    @Around("execution(* com.ys.modules..controller..*(..))")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        Exception ex = null;
        try {
            result = joinPoint.proceed();
            return result;
        } catch (Exception e) {
            ex = e;
            throw e;
        } finally {
            try {
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                String apiName = signature.getMethod().getName();
                ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attrs != null ? attrs.getRequest() : null;
                String path = request != null ? request.getRequestURI() : "";
                String params = request != null ? request.getQueryString() : "";
                String operator = request != null ? request.getHeader("operator") : "";
                OperationLog log = new OperationLog();
                log.setApiName(apiName);
                log.setPath(path);
                log.setParams(params);
                log.setResult(result != null ? result.toString() : (ex != null ? ex.getMessage() : ""));
                log.setOperateTime(new Date());
                log.setOperator(operator);
                operationLogService.save(log);
            } catch (Exception logEx) {
                log.error("记录操作日志异常", logEx);
            }
        }
    }
} 